import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_layout/tools/print_utils.dart';
import 'package:logger/logger.dart';

class HttpPage extends StatefulWidget {
  const HttpPage({Key? key}) : super(key: key);

  @override
  _HttpPageState createState() => _HttpPageState();
}

class _HttpPageState extends State<HttpPage> {
  String baseUrl = "http://www.wanandroid.com/";

  Future<String>? _future;

  bool isError = true;

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("网络请求"),
        ),
        body: FutureBuilder(
            future: _future,
            initialData: "初始化",
            builder: (context, snapshot) {
              PrintUtils.printByApp(snapshot, level: Level.error);
              var widget;
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  //如果出现错误
                  widget = Center(
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          isError = !isError;
                          loadData();
                        });
                      },
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: const [
                          Icon(
                            Icons.error,
                            color: Colors.red,
                            size: 48,
                          ),
                          Text("啊呜~~~ 加载失败")
                        ],
                      ),
                    ),
                  );
                } else {
                  widget = SingleChildScrollView(child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text("${snapshot.data?.toString()}"),
                  ));
                }
              } else {
                widget = const Center(
                  child: Padding(
                    padding: EdgeInsets.all(20),
                    child: CircularProgressIndicator(),
                  ),
                );
              }
              return widget;
            }));
  }

  void loadData() {
    _future = Future.delayed(const Duration(milliseconds: 100), () async {
      var httpResult = await Dio().get("${baseUrl}article/list/0/json").then((value) {
        // PrintUtils.printByApp(value.data, level: Level.info);
        if (isError) {
        } else {
          return value.data.toString();
        }
      });
      return httpResult!;
    });
  }
}
